import * as echarts from '../lib/ec-canvas/echarts';
var t = getApp()
let chart = null;
function initChart(canvas, width, height, dpr,arr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option1 = {
    title: {
      text: '',
      left: 'center'
    },
    legend: {
      data: ['热度', '正面', '负面'],
      orient: 'horizontal',
      x:'center',
      y:'bottom'
    },
    grid: {
      top: 15,   // 等价于 y: '16%'
      left: 15, 
      right: 15,
      bottom: 15,
      containLabel: true
  },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      axisLabel: {
        rotate: 0, // 旋转角度
        interval: 0  //设置X轴数据间隔几个显示一个，为0表示都显示
        },
      data: [],
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      show:false,
      axisLabel : {
          formatter: function(){
              return "";
          }
      }

    },
    series: [{
      type: 'bar',
      smooth: true,
      barWidth : 20,
      showAllSymbol: false,
      axisTick:{
        show:false
      },
      name: '客流量',
      areaStyle: {
        normal: {color: '#d9ecfa'}
     },
     itemStyle : {  
        normal : {  
            lineStyle:{  
                color:'#0ab5f5'  
            }  
        }  
    },
      data: []
    }]
  };

  chart.setOption(option1);
  return chart;
}
Page({
  data: {
    bannar:['/images/index_bannar.png','/images/index_bannar.png','/images/index_bannar.png'],
    store_id:'',
    list:[],
    iconsUrl:t.globalData.iconsUrl,
    ec: {
      onInit: initChart
    },
    navHeight:t.globalData.navHeight,
    title:'门店详情',
    //弹窗 
    showStatus:false,
    showPhone:false,  //手机获取弹窗
    showXieyi:false,
		show: false,
		showImage:false,//自动工位弹窗
    duration: 300, //动画时长，单位毫秒
    position: 'bottom',
    round: true,  //是否显示圆角
    overlay: true, //是否显示遮罩层
    customStyle: '',//自定义弹出层样式
    overlayStyle: '', //自定义遮罩层样式
    // 基本信息里的下箭头
    dStatus:false,
    code:'',
    // 工位
    siteList:[],
    // 扫码核销
    result:'',
		rawData:'',
		tipStatus:false,
		// 核销成功弹窗定时器
		interval:"",//定时器
		seconds:3, //倒计时3秒
		site:{}
  },
  onLoad: function (options) {
    this.setData({
      store_id:options.store_id,
      dis:options.dis
    })
  },
  onShow: function () {
    this.getInfo()
    // 获取工位信息
    this.getSite()
	},
	
  // 扫码核销
  saoma:function(){
    wx.scanCode({
      success: (res) => {
        console.log(res)
        this.setData({
          result:res.result,
          rawData:res.rawData,
        })
        this.submitXieyi()
      },
      fail: (err) => {
        console.log(err, 'fail')
      }
    })
  },
  //用户协议 
  to_user(){
    wx.navigateTo({
      url: '/pages/article/article?id=334',
    })
  },
  // 跳转到手机授权页面
  showTelLogin(){
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  // 
  exit() {
    this.setData({show: false,showStatus:false,showXieyi:false,showPhone:false,showImage:false})
  },
  // 手机号 暂不登录按钮
  exitback() {
    this.setData({showPhone: false})
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //电话登录
  getPhoneNumber(e){
    const that = this,
      iv = e.detail.iv,
      da = e.detail.encryptedData;
    if (!e.detail.encryptedData) return wx.showToast({ title: '授权失败,请重新授权！',icon:'none'})
    // 请求接口
    wx.login({
      success(e){
        console.log(e);
        wx.showLoading({
          title: '请稍后',
        })
        t.request('/login/getPhoneNumber',{code: e.code,iv:iv,encryptedData:da},function(event){
          wx.hideLoading({})
          if (event.code!==200) return wx.showToast({ title: event.msg,icon:'none' })
          if (event.code==200) {
            wx.setStorageSync('tel', event.result.phoneNumber)
            t.globalData.show_tel_login =false
            that.exit()
          }
        })
      }
    })
  },
  // 底部弹出核销
  popup(e) {
    if (t.globalData.show_tel_login) {
      this.showTelLogin()
      return;
    }
    this.setData({
      showXieyi:false,
      show: true,
      code:'',
    })
  },
  // 提交核销-弹出协议
  submitXieyi(){
    if(this.data.code == '' && this.data.result ==''){
      return false
    }
    this.setData({
      showXieyi:true
    })
  },
  // 提交核销码
  submitCoupon(){
    var that = this
    if(that.data.btnloading){
      return false;
    }
    var o = {
      code: that.data.code,
      result:that.data.result,
      rawData:that.data.rawData,
      b_id:that.data.list.b_id,
      store_id:that.data.list.store_id,
      distance:that.data.list.distance
    }
    that.setData({
      btnloading:true,
      showXieyi:false,
      result:'',
      rawData:'',
    })
    t.request('/settle/DouyinAfterVerification',o,function(e){
      console.log(e)
      // t.showSuccess(e.msg)
      that.setData({
        btnloading:false
      })
      if(e.code == 200){
				// 设置读秒器
				that.data.interval = setInterval(() => {
					setTimeout(that.intervalFun, 0);
				}, 1000)
        // 跳转到成功页面
        that.setData({
            info:e.result,
            show:false,
						showStatus:true,
						seconds:3,
            code:''
        })
      }else{
        // 错误提示
        wx.showModal({
          title: '提示',
          content: e.msg,
          cancelText:'关闭'
        })
      }
     
    })
  },
  // input code
  bindCodeInput: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    this.getInfo()
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
    setTimeout(function () {
      // 不加这个方法真机下拉会一直处于刷新状态，无法复位
      wx.stopPullDownRefresh()
    }, 1000)
  },
  // 工位信息
  getSite(){
    let that = this
    t.request('/store/siteData',{store_id:this.data.store_id},function(res){
      if(res.code==200) {
        var list = res.result
        that.setData({siteList:list})
      }
    })
  },
  // 店铺信息
  getInfo(e){
    var that = this
    t.request('/store/getOne',{store_id:this.data.store_id},function(res){
      if (res.code==200) {
        var list = res.result
        that.setData({list:list})
        // 如果有余额，判断是否绑定车辆
        if(res.result.balance != 0 && res.result.cars == 0){
          that.login = that.selectComponent("#login")
          that.login.show_login()
        }
        //list.in
        console.log(list.time);
        setTimeout(() => {
          chart.setOption({
            xAxis: {
              data: list.time,
            },
            series: [{
              data: list.in,
              itemStyle: {   
                  normal:{  
    　　　　　　　　　　　　//每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                      color: function (params){
                          var colorList = list.colour;
                          return colorList[params.dataIndex];
                      }
                  },
              },
            }]
          })
        }, 1000);
      }
    })
  },
  // 拨打客服电话
  call(e){
    wx.makePhoneCall({
      phoneNumber: this.data.list.tel,
    }).catch((e) => {
      console.log(e) 
    })
  },
  showDetail(){
    this.setData({
      dStatus:!this.data.dStatus
    })
  },
  // 充值按钮
  invest(e){
    if (t.globalData.show_tel_login) {
      this.showTelLogin()
      return;
    }
    wx.navigateTo({
      url: '/pages/personCenter/chooseStore/invest/invest?store_id=' + this.data.store_id ,
    })
  },
  // 开始洗车
  start_btn(e){
    let that =this
		let site_id = e.currentTarget.dataset.id //工位ID
		let is_auto = e.currentTarget.dataset.auto //是否是全自动洗车工位
    wx.getLocation({
      type: 'gcj02',
      success (res) {
        that.to_wash(site_id,res.latitude,res.longitude,is_auto)
      },
      fail: function (res) {
        console.info('ready getLocation fail=' + JSON.stringify(res))
        // ----------------------------------------------------------
          // 判断用户是否拒绝了授权
          wx.getSetting({
            success: res => {
              if (typeof(res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
                // 用户拒绝了授权
                wx.showModal({
                  title: '提示',
                  content: '您拒绝了定位权限，将无法使用门店功能',
                  success: res => {
                    if (res.confirm) {
                      // 跳转设置页面
                      wx.openSetting({
                        success: res => {
                          if (res.authSetting['scope.userLocation']) {
                            // 授权成功，重新定位
                            wx.getLocation({
                              type: 'gcj02',
                              success: res => {
                                that.to_wash(site_id,res.latitude,res.longitude,is_auto)
                              },
                              fail: function (res) {
                                wx.showToast({
                                  title: '请开启手机定位服务以提供更好的体验',
                                  icon: 'none',
                                  duration: 5500,
                                });
                                console.error('获取位置信息失败：',res);
                               }
                            });
                          } else {
                            // 没有允许定位权限
                            wx.showToast({
                              title: '您拒绝了定位权限，将无法使用门店功能',
                              icon: 'none'
                            });
                          }
                        }
                      });
                    }
                  }
                });
              }
            }
          });
        // ------------------------------------------------------------
       }
    })
 },

  // 跳转洗车入场页面（前置方法做个判断用）
  to_wash(site_id,lat,lng,is_auto=0){
		// 全自动洗车弹出须知弹窗
    if(is_auto==1){
			this.setData({
				showImage:true,
				site:{
					site_id,lat,lng
				}
			})
		}else{
			this.to_wash_d(site_id,lat,lng)
		}
	},
	// 须知按钮
	to_wash_c(){
		this.setData({
			showImage:false,
		 })
		let site =this.data.site
		this.to_wash_d(site.site_id,site.lat,site.lng)
	},
	 // 跳转洗车入场页面
	 to_wash_d(site_id,lat,lng){
		let that = this
    let o={lat,lng,store_id:that.data.store_id,site_id}
    t.request('/store/nowDistance',o,function(e){
      console.log(e)
      if(e.code == 200){
        wx.showModal({
          title: '提示',
          content: 
          e.result.show_text,
          cancelText:'取消',
          success (res) {
            if (res.confirm) {
              if(e.result.is_allow==1){
                // 跳转到成功页面
                wx.navigateTo({
                  url: '/pages/code_start/code_start?ismini=1&store=' + that.data.store_id +'&site=' + site_id,
                })
              } 
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }else{wx.showModal({title: '提示',content: e.msg,cancelText:'关闭'})}// 错误提示
      
    })
	 },
  // 导航
  to_map(e){
    if (t.globalData.show_tel_login) {
      this.showTelLogin()
      return;
    }
    var list=this.data.list
    wx.getLocation({
      type: 'wgs84', 
      success: function (res) {
        wx.openLocation({
          latitude: +list.lat,
          longitude: +list.lng,
          name: list.title,
          address: list.address
        })
      }
    })
	},
	
	// 余额注释弹窗
	show_tip(){
		let that = this
		that.setData({
			tipStatus : !this.data.tipStatus
		})
		if(that.data.tipStatus == true){
			setTimeout(function () {
				// 不加这个方法真机下拉会一直处于刷新状态，无法复位
				that.close_tip()
			}, 5000)
		}
		// wx.showToast({
		// 	title:'本店可用余额+其它可在本店通用的余额之和',
		// 	icon: "none",
		// 	mask:true,
		// 	duration: 5000
		// })
	},
	// 关闭提示
	close_tip(){
		this.setData({
			tipStatus : false
		})
	},
	// 读秒器
	intervalFun(){
		console.log('读秒器')
		let that =this
		if(that.data.seconds<1){
			clearInterval(that.data.interval)
			that.exit()
		}else{
			that.setData({
				seconds:that.data.seconds-1
			})
		}
	}
})